<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController {


/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$users = $this->User->User->find('list');
		$facebooks = $this->User->Facebook->find('list');
		$twitters = $this->User->Twitter->find('list');
		$this->set(compact('users', 'facebooks', 'twitters'));
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->User->read(null, $id);
		}
		$users = $this->User->User->find('list');
		$facebooks = $this->User->Facebook->find('list');
		$twitters = $this->User->Twitter->find('list');
		$this->set(compact('users', 'facebooks', 'twitters'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->User->delete()) {
			$this->Session->setFlash(__('User deleted'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('User was not deleted'));
		$this->redirect(array('action' => 'index'));
	}
	
	/**
	 * Create new record in tblreset_password and send mail to user
	 */
	public function reset_password() {
		$this->layout = false;
		$this->autoRender = false;
		$user = $this->params->query['user'];
		$this->loadModel('ResetPassword');
		$hit = false;
		
		if ($user) {
			$this->User->recursive = -1;
			// Generate token key
			$newToken = $this->generatePassword(45);
			while ($this->ResetPassword->find('first', array('conditions' =>  array('ResetPassword.token_key' => $newToken))) != null) {
				$newToken = $this->generatePassword(45);
			}
			$link = Router::url('/users/confirm_reset_password?token=' . $newToken, true);
			// Check user_name
			$hitUser = $this->User->find('first', array('conditions' => array('User.user_name' => $user)));
			if ($hitUser != null) {
				$hit = true;
				$content = "Hi "
				. $hitUser['User']['user_name'] . PHP_EOL
				. "If you'd like to reset your password for Xcomic, please click on the following link: ". PHP_EOL. PHP_EOL
				. $link . PHP_EOL . PHP_EOL
				. "If you have not requested to reset your password, we apologize -- please forward this email to "
				. SYSTEM_EMAIL_ADDRESS . " to let us know. " . PHP_EOL . PHP_EOL
				. "Many thanks," . PHP_EOL . "The Xcomic team.";
				
				$this->send_email($hitUser['User']['email'], $content);
				if ($this->save_reset_password($hitUser['User']['user_id'], $newToken)) {
					$array = array("is_success"=> true, "message"=> "API-SUCCESS-200");
					echo json_encode($array);
				} else {
					$array = array("is_success"=> false, "message"=> "create token error");
					echo json_encode($array);
				}
				
			} else {
				// Check email
				$hitUser = $this->User->find('first', array('conditions' => array('User.email' => $user)));
				if ($hitUser != null) {
					$hit = true;
					$content = "Hi "
					. $hitUser['User']['user_name'] . PHP_EOL
					. "If you'd like to reset your password for Xcomic, please click on the following link: ". PHP_EOL. PHP_EOL
					. $link . PHP_EOL . PHP_EOL
					. "If you have not requested to reset your password, we apologize -- please forward this email to "
					. SYSTEM_EMAIL_ADDRESS . " to let us know. " . PHP_EOL . PHP_EOL
					. "Many thanks," . PHP_EOL . "The Xcomic team.";
					
					$this->send_email($hitUser['User']['email'], $content);
					if ($this->save_reset_password($hitUser['User']['user_id'], $newToken)) {
						$array = array("is_success"=> true, "message"=> "API-SUCCESS-200");
						echo json_encode($array);
					} else {
						$array = array("is_success"=> false, "message"=> "create token error");
						echo json_encode($array);
					}
				}
			}
		}
		
		// Error when email or user_name is not exist
		if (!$hit) {
			$array = array("is_success"=> false, "message"=> "invalid user or email");
			echo json_encode($array);
		}
	}
	
	/**
	 * Confirm to reset password
	 */
	public function confirm_reset_password() {
		$this->autoRender = false;
		$this->layout = false;
		$token = $this->params->query['token'];
		$this->loadModel('ResetPassword');
		$hitToken = $this->ResetPassword->find('first', array('conditions' => array('ResetPassword.token_key' => $token)));
		if ($hitToken != null) {
			$newPassword = $this->generatePassword(6);
			$user = $this->User->find('first', array('conditions' => array('User.user_id' => $hitToken['ResetPassword']['user_id'])));
			$this->User->id = $hitToken['ResetPassword']['user_id'];
			$this->User->saveField('password', $newPassword);
// 			$this->User->updateAll(array('User.password'=> $newPassword), array('User.user_id' => $hitToken['ResetPassword']['user_id']));
			// Send successfull reset password to user
			$this->send_email($user['User']['email'], $user['User']['user_name'] . ' reset password successfull ' . PHP_EOL . 'new password : ' . $newPassword);
			$this->ResetPassword->id = $token;
			$this->ResetPassword->delete();
			echo 'Successfull ! please, check mail to get new password';
		} else {
			echo 'Unsuccessfull !';
		}
	}
	
	
	/**
	 * Send email
	 * 
	 * @param unknown_type $email
	 * @param unknown_type $content
	 */
	public function send_email($toEmail, $content) {
		if ($toEmail != null) {
			$email = new CakeEmail('gmail');
			$email->from(array(SYSTEM_EMAIL_ADDRESS => 'Xcomic'));
			$email->to($toEmail);
			$email->subject('Xcomic reset password');
			$email->send($content);
		}
	}
	
	public function save_reset_password($id, $token_key) {
		$this->loadModel('ResetPassword');
		$this->ResetPassword->create();
		$resetPassword = array('user_id' =>$id,  'token_key' => $token_key, 'expired_date' => date('Y-m-d H:i:s', strtotime('+10 days')));
		if ($this->ResetPassword->save($resetPassword)) {
			return true;
		} else {
			return false;
		}
	}
	function generatePassword ($length = 8) {
	
		// start with a blank password
		$password = "";
	
		// define possible characters - any character in this string can be
		// picked for use in the password, so if you want to put vowels back in
		// or add special characters such as exclamation marks, this is where
		// you should do it
		$possible = "012346789bcdfghjkmnpqrtvwxyz";
	
		// we refer to the length of $possible a few times, so let's grab it now
		$maxlength = strlen($possible);
	
		// check for length overflow and truncate if necessary
		if ($length > $maxlength) {
			$length = $maxlength;
		}
	
		// set up a counter for how many characters are in the password so far
		$i = 0;
	
		// add random characters to $password until $length is reached
		while ($i < $length) {
	
			// pick a random character from the possible ones
			$char = substr($possible, mt_rand(0, $maxlength-1), 1);
	
			// have we already used this character in $password?
			if (!strstr($password, $char)) {
				// no, so it's OK to add it onto the end of whatever we've already got...
				$password .= $char;
				// ... and increase the counter by one
				$i++;
			}
	
		}
	
		// done!
		return $password;
	
	}
}
